﻿using ModbusDataParseTool.Entity;
using MyUtility.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ModbusDataParseTool.Service
{
    public class ParseDataService
    {

        public bool ParseDataByUnit(string inputStrData, ModbusProtocolEntity modbusProtocolEntity, out string ProtocolData)
        {
            bool isRight = false;

            ProtocolData = "";

            StringBuilder stringBuilder = new StringBuilder();

            if (string.IsNullOrEmpty(inputStrData))
            {
                return isRight;
            }
            inputStrData = Regex.Replace(inputStrData, @"\s", ""); 

            stringBuilder.AppendLine("解析时间：" + DateTime.Now);
            //开始
            stringBuilder.AppendLine("协议名称：" + modbusProtocolEntity.ProtocolName);
            foreach (ProtocolUnit item in modbusProtocolEntity.ProtocolUnits)
            {
                stringBuilder.Append(item.Name + "\t");
                int endIndex = item.StartIndex + item.Length;
                if (inputStrData.Length <= endIndex)
                {
                    stringBuilder.AppendLine("长度不足");
                    continue;
                }
                string strTemp = inputStrData.Substring(item.StartIndex, item.Length);
                stringBuilder.Append("上送值：" + strTemp + "\t");
                string dataChange = "";
                switch (item.ChangeMode)
                {
                    case DataChangeMode.Fix:
                        break;
                    case DataChangeMode.HexLittle:
                        dataChange = ChangHexStr(strTemp, item.Magnification);
                        stringBuilder.Append("转换值：" + dataChange);
                        break;
                    case DataChangeMode.HexLarge:
                        dataChange = ChangHexStr(strTemp, item.Magnification, true);
                        stringBuilder.Append("转换值：" + dataChange);
                        break;
                    default:
                        break;
                }
                stringBuilder.AppendLine("\t");
            }
            isRight = true;
            ProtocolData = stringBuilder.ToString();

            return isRight;
        }


        private string ChangHexStr(string oldStr, decimal magnification, bool isLargeHex = false)
        {
            string newStr = "";
            if (isLargeHex)
            {
                oldStr = MyUtility.Utility.StringSplit.StrToLittleEndianNoSpace(oldStr);
            }
            if (CheckStrNum.CheckStrIsHexInteger(oldStr))
            {
                int value = Convert.ToInt32(oldStr, 16);
                decimal realvalue = value * magnification;
                newStr = realvalue.ToString();
            }
            else
            {
                newStr = "格式错误";
            }

            return newStr;
        }

    }
}
